﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace AiMoWindows.Windows.Scripts.ViewModels
{
    /// <summary>
    /// RenameSymbolDialog.xaml 的交互逻辑
    /// </summary>
    partial class RenameSymbolDialog : UserControl, INotifyPropertyChanged
    {
        private static readonly Regex _identifierRegex = IdentifierRegex();

        private string? _symbolName;

        public RenameSymbolDialog()
        {
            DataContext = this;
            InitializeComponent();
        }

        public bool ShouldRename { get; private set; }

        public string? SymbolName
        {
            get => _symbolName;
            set
            {
                _symbolName = value;
                OnPropertyChanged();
            }
        }

        bool ResultNameIsValid => SymbolName != null && _identifierRegex.IsMatch(SymbolName);

        private void Rename_Click(object? sender, RoutedEventArgs e)
        {
            ShouldRename = ResultNameIsValid;
            Close();
        }

        private void Cancel_Click(object? sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SymbolText_KeyDown(object? sender, KeyEventArgs e)
        {
            RenameButton.IsEnabled = ResultNameIsValid;
            if (e.Key == Key.Enter)
            {
                if (RenameButton.IsEnabled)
                {
                    e.Handled = true;
                    ShouldRename = true;
                    Close();
                }
            }
            else if (e.Key == Key.Escape)
            {
                e.Handled = true;
                Close();
            }
        }

        public Task<bool> ShowDialog(int left, int top, string symbolName)
        {
            SymbolTextBox.SelectionStart = symbolName.Length;
            SymbolName = symbolName;
            Canvas.SetLeft(this, left);
            Canvas.SetTop(this, top);
            Visibility = Visibility.Visible;
            SymbolTextBox.Focus();
            SymbolTextBox.SelectAll();
            return Task.Run(() =>
            {
                while (Visibility == Visibility.Visible)
                {
                    Thread.Sleep(100);
                }
                return true;
            });
        }

        public void Close()
        {
            Visibility = Visibility.Collapsed;
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        [GeneratedRegex(@"^(?:((?!\d)\w+(?:\.(?!\d)\w+)*)\.)?((?!\d)\w+)$")]
        private static partial Regex IdentifierRegex();
    }
}
